/**
 * 每个db类需要继承此类
 */
package com.yinhe.music.yhmusic.db;


import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.table.DatabaseTableConfig;
import com.yinhe.music.yhmusic.log.MLog;

import java.sql.SQLException;

/**
 * @author daixiang
 *
 */
public abstract class AbstractBaseDb  {

	private DbHelper mDbHelper;
	protected AbstractBaseDb(DbHelper dbHelper) {
		super();
		mDbHelper = dbHelper;
	}

	/**
	 * 为保证线程安全，此函数应该只在command的execute函数里调用（在DbThread执行）
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected <D extends Dao<T, ?>, T> D getDao(Class<T> cls) {
		Dao<?, ?> dao = null;
		if (mDbHelper != null) {
			if (cls != null) {
				try {
					dao = (D)mDbHelper.getDao(cls);
					//logger.info("created dao for " + cls.getSimpleName());
				} catch (SQLException e) {
					MLog.error(this, "cannot getDao for class " + cls.getName(), e);
				}
			}
		}
		return (D) dao;
	}

    protected <D extends Dao<T, ?>, T> D getDaoWithConfig(DatabaseTableConfig<T> config){
        Dao<?, ?> dao = null;
        if (mDbHelper != null) {
            if (config != null) {
                try {
                    dao = (Dao<?, ?>)DaoManager.createDao(mDbHelper.getConnectionSource(), config);
                    //logger.info("created dao for " + cls.getSimpleName());
                } catch (SQLException e) {
                    MLog.error(this, "cannot getDao for class with config" + config);
                }
            }
        }
        return (D) dao;
    }

    protected <D extends Dao<T, ?>, T> D getDaoNoCacheWithConfig(DatabaseTableConfig<T> config){
        D dao = getDaoWithConfig(config);
        if(mDbHelper != null) {
            DaoManager.unregisterDao(mDbHelper.getConnectionSource(), dao);
        }
        return dao;
    }
}
